// ZXCameraWraper.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include <ZXVNMSClientSdk.h>

#include "ZXCameraWraper.h"
#include <opencv\cv.h>
#include <opencv2\opencv.hpp>
#include <vector>
#include <string.h>
using namespace std;
using namespace cv;


#pragma comment(lib, "vfw32.lib" ) 
#pragma comment(lib, "IlmImf.lib" )   
#pragma comment(lib, "libjasper.lib" )  
#pragma comment(lib, "libjpeg.lib" )  
#pragma comment(lib, "libpng.lib" )  
#pragma comment(lib, "libtiff.lib" ) 
#pragma comment(lib, "zlib.lib" ) 
#pragma comment(lib, "opencv_core249.lib" )   
#pragma comment(lib, "opencv_objdetect249.lib" )  
#pragma comment(lib, "opencv_highgui249.lib" )  
#pragma comment(lib, "opencv_imgproc249.lib" ) 

#pragma comment(lib, "ZxvnmsSDK.lib" ) 

int getlen(const char *result) {
	int i = 0;
	while (result[i] != '\0') {
		i++;
	}
	return i;
}

extern "C" UNMANAGEDDLL_API int GetCameras(const char* server,int port,const char* userName,const char* pwd,int startIndex,
	int maxCameraCount, CameraItem* cameras)
{
	int ret = -1;
	int tem_index = -1;
	int index = 0;
	int count = 0;
	int len = 0;
	//ret = ZXVNMS_Init();
	//if (ret != 0)
 //      return ret;
	//int sessionHandle=ZXVNMS_InitSession(server, port,userName,pwd,0,"","",0);
	//if (sessionHandle<0)
	//{
	//	return count;
	//}
	if (ZXVNMS_QueryDevicesForDomain(ZXVNMS_DevType::CAMERA, "") == 0)
	{
		while (ZXVNMS_MoveNext()!=-1)
		{
			tem_index++;
			if (tem_index >=startIndex)
			{
				if (count<maxCameraCount)
				{
					count++;
					const char* device_name = ZXVNMS_GetValueStr(ZXVNMS_Camera::device_name);
					const char* cameraId = ZXVNMS_GetValueStr(ZXVNMS_Camera::device_id);
					len = getlen(cameraId);
					len = len < CHAR_LEN ? len : CHAR_LEN;
					memcpy(cameras[index].cameraId, cameraId, len);
					len = getlen(device_name);
					len = len < CHAR_LEN ? len : CHAR_LEN;
					memcpy(cameras[index].cameraName, cameraId, len);

				}
				else
				{
					break;
				}
			}

		}
	}
	return count;
}


extern  "C" UNMANAGEDDLL_API	int PlayVideo(const char* cameraID, long hWnd)
{
	return ZXVNMS_PlayVideo(cameraID, hWnd);
}

extern "C" UNMANAGEDDLL_API bool YV12ToBGR24_OpenCV(unsigned char* pYUV, 
	unsigned char* pBGR24, int width, int height, int pBGR24BufferLen)
{
	if (width < 1 || height < 1 || pYUV == NULL || pBGR24 == NULL)
		return false;
	Mat dst(height, width, CV_8UC3, pBGR24);
	Mat src(height + height / 2, width, CV_8UC1, pYUV);
	cvtColor(src, dst, CV_YUV2RGB_I420);
	if (pBGR24BufferLen != dst.total())
		return false;
	memcpy(pBGR24, dst.data, dst.total());
	return true;
}